//pending fulfilled rejected
class _Promise {
    constructor(fn) {
        // 成功
        this.state = 'pending'
        this.value = undefined // 初始值
        this.reason = undefined // 失败原因
        this.onFulfilledfn = [] // 存放成功的数组
        this.onRejectedfn = [] // 存放失败的数组
        let resolve = (value) => {
            if (this.state === 'pending') {
                this.state = 'fulfilled'
                this.value = value
                this.onFulfilledfn.forEach((fn) => {
                    fn()
                })
            }
        }
        // 失败
        let reject = (reason) => {
            if (this.state === 'pending') {
                this.state === 'reject'
                this.reason = reason
                this.onRejectedfn.forEach((fn) => {
                    fn()
                })
            }
        }
        // 立即执行
        try {
            fn(resolve, reject)
        } catch (error) {
            reject(error)
        }
    }
    then(onFulfilled, onRejected) {
        if (this.state === 'fulfilled') {
            onFulfilled(this.value)
        }
        if (this.state === 'rejected') {
            onRejected(this.value)
        }
        // 添加到执行数组里面
        if (this.state === 'pending') {
            this.onFulfilledfn.push(() => {
                onFulfilled(this.value)
            })
            this.onRejectedfn.push(() => {
                onRejected(this.value)
            })
        }
    }
}

let p = new _Promise(function(resolve, reject) {
    console.log('执行');
    setTimeout(() => {
        resolve(3)
    }, 1000)
})

p.then(function(res) {
    console.log(res);
}, function(err) {
    console.log(err);
})